package com.example.padlock.view.activity;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.padlock.R;
import com.example.padlock.data.api.HttpApi;
import com.example.padlock.data.api.HttpApi.OnFetched;
import com.example.padlock.data.bean.UrlBean;
import com.example.padlock.data.entity.AdResultEntity;
import com.example.padlock.data.entity.AdResultEntity.AdEntity;
import com.example.padlock.data.entity.CallResultEntity;
import com.example.padlock.view.callui.DialogWidget;
import com.example.padlock.view.callui.PayPasswordView;
import com.example.padlock.view.callui.PayPasswordView.OnPayListener;
import com.example.padlock.view.sendvedio.ConnectThread;
import com.example.padlock.view.sendvedio.PadEntity;
import com.example.padlock.view.sendvedio.ConnectThread.OnSendListener;
import com.example.padlock.view.service.ScrollTask;
import com.example.padlock.view.util.NetworkUtils;
import com.example.padlock.view.widget.ViewPagerScroller;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;

public class MainActivity extends Activity implements OnClickListener,OnSendListener{

	private OnFetched mOnFetched;
	private ArrayList<View> mDots1 = new ArrayList<View>();
	private List<View> mVpItems1;
	private ViewPager vpActivate;
	private LinearLayout mDotLayout;
	private List<ImageView> imgDots;
	private ScheduledExecutorService scheduledExecutorService;
	
	private Button btnCall;
	private DialogWidget mDialogWidget;
	private ConnectThread thread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initView();
		setClickListener();
		onFetched();
		getAd();
//		thread=new ConnectThread("115.29.176.161", 31500);
//        thread.setOnSendListener(this);
//        thread.start();
	}

	private void initView() {
		setContentView(R.layout.activity_main);
		vpActivate = (ViewPager) findViewById(R.id.activity_main_ad_container);
		ViewPagerScroller scroller = new ViewPagerScroller(this);
		scroller.setmDuration(1500);
		scroller.initViewPagerScroll(vpActivate);
		vpActivate.setOnPageChangeListener(new CallOutListener());
		mDotLayout=(LinearLayout)findViewById(R.id.fragment_activate_the_lock_dotLayout);
		btnCall=(Button)findViewById(R.id.activity_main_call);
	}
	
	private void setClickListener(){
		btnCall.setOnClickListener(this);
	}

	public void getAd() {
		if (!NetworkUtils.isNetUseful(this)) {
			return;
		}
		System.out.println("code:"
				+ Secure.getString(getContentResolver(), Secure.ANDROID_ID));
		new HttpApi(mOnFetched).getAd("8a7f5b7d1322a8b4");
		new HttpApi(mOnFetched).call("8a7f5b7d1322a8b4", "101");
		//new HttpApi(mOnFetched).postAliveState("8a7f5b7d1322a8b4");
	}

	public void onFetched() {
		mOnFetched = new OnFetched() {

			@Override
			public void onAdFetched(AdResultEntity adResult) {
				if (adResult.getAdvertisementList() == null
						|| !(adResult.getAdvertisementList().size() > 0)) {
					return;
				}
//				MyPagerAdapter adapter = new MyPagerAdapter(
//						adResult.getAdvertisementList());
//				vpActivate.setAdapter(adapter);
//				scheduledExecutorService = Executors
//						.newSingleThreadScheduledExecutor();
//				// 当Activity显示出来后，每两秒钟切换一次图片显示
//				scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(
//						vpActivate, adResult.getAdvertisementList()), 1, 2,
//						TimeUnit.SECONDS);
			}
			
			@Override
			public void onCall(CallResultEntity callResult) {
				// TODO Auto-generated method stub
				super.onCall(callResult);
				System.out.println("call:"+callResult.getComment());
			}

			@Override
			public void onFail(String msg) {
				// TODO Auto-generated method stub
				super.onFail(msg);
			}

		};
	}

	/**
	 * 添加滑动标志点
	 * 
	 * @param list
	 */
	private void setDots(List<AdEntity> list) {
		imgDots = new ArrayList<ImageView>();
		for (int i = 0; i < list.size(); i++) {
			ImageView iv = new ImageView(this);
			iv.setLayoutParams(new LayoutParams(10, 10));
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					20, 20);
			layoutParams.setMargins(5, 0, 5, 0);
			iv.setLayoutParams(layoutParams);
			if (i == 0) {
				iv.setBackgroundResource(R.drawable.dot_focused);
			} else {
				iv.setBackgroundResource(R.drawable.dot_normal);
			}
			mDotLayout.addView(iv);
			imgDots.add(iv);
		}
	}

	private class CallOutListener implements ViewPager.OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			for (int i = 0; i < imgDots.size(); i++) {
				if (arg0 != i) {
					imgDots.get(i).setBackgroundResource(R.drawable.dot_normal);
				} else {
					imgDots.get(i)
							.setBackgroundResource(R.drawable.dot_focused);
				}
			}
		}
	}

	private class MyPagerAdapter extends PagerAdapter {

		private List<AdEntity> mList;
		private List<ImageView> mViewList;

		public MyPagerAdapter(List<AdEntity> list) {
			this.mList = list;
			setDots(mList);
			mViewList = new ArrayList<ImageView>();
			for (int i = 0; i < list.size(); i++) {
				ImageView iv = new ImageView(MainActivity.this);
				iv.setScaleType(ScaleType.FIT_XY);
				mViewList.add(iv);
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			// TODO Auto-generated method stub
			((ViewPager) container).removeView(mViewList.get(position));
		}

		@Override
		public Object instantiateItem(View container, int position) {
			// TODO Auto-generated method stub
			System.out.println("adapter:" + mList.get(position).getUrl() + "iv"
					+ mViewList.get(position));
			ImageLoader.getInstance().displayImage(
					UrlBean.BASE_PATH + mList.get(position).getUrl(),
					mViewList.get(position));
			// mViewList.get(position).setImageResource(R.drawable.ic_launcher);
			((ViewGroup) container).addView(mViewList.get(position));
			return mViewList.get(position);
		}
	}

	@Override
	public void onClick(View v) {
		mDialogWidget=new DialogWidget(MainActivity.this, getDecorViewDialog());
		mDialogWidget.show();
		//thread.disConnect();
	}
	
	protected View getDecorViewDialog() {
		// TODO Auto-generated method stub
		return PayPasswordView.getInstance("45.99",this,new OnPayListener() {
			
			@Override
			public void onSurePay(String password) {
				// TODO Auto-generated method stub
				if(mDialogWidget!=null){
					mDialogWidget.dismiss();
					mDialogWidget=null;
					Toast.makeText(getApplicationContext(), "正在呼叫...", Toast.LENGTH_SHORT).show();
				}
				Intent intent=new Intent(MainActivity.this, SendVedioActivity.class);
				startActivity(intent);
			}
			
			@Override
			public void onCancelPay() {
				// TODO Auto-generated method stub
				mDialogWidget.dismiss();
				mDialogWidget=null;				
			}
		}).getView();
	}

	@Override
	public void onSend(OutputStream os) {
		System.out.println("call:"+"calling");
		try {
			os.write("bd".getBytes());
			os.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
